<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>考试详情</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text" 
          @click="goBack">
          返回列表
        </el-button>
      </div>
      
      <div v-loading="loading">
        <div class="exam-header">
          <h2 class="exam-title">{{ exam.title }}</h2>
          <el-tag :type="getStatusType(exam.status)">{{ exam.statusName }}</el-tag>
        </div>
        
        <el-divider></el-divider>
        
        <div class="exam-info">
          <div class="info-row">
            <div class="info-item">
              <span class="label">学科：</span>
              <span>{{ exam.subjectName }}</span>
            </div>
            <div class="info-item">
              <span class="label">教育阶段：</span>
              <span>{{ exam.educationLevelName }}</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item">
              <span class="label">试卷：</span>
              <span>{{ exam.paperTitle }}</span>
            </div>
            <div class="info-item">
              <span class="label">总分：</span>
              <span>{{ exam.totalScore }} 分</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item">
              <span class="label">考试时长：</span>
              <span>{{ exam.duration }} 分钟</span>
            </div>
            <div class="info-item">
              <span class="label">学校：</span>
              <span>{{ exam.schoolName || '所有学校' }}</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item full-width">
              <span class="label">考试时间：</span>
              <span>{{ formatDateTime(exam.startTime) }} 至 {{ formatDateTime(exam.endTime) }}</span>
            </div>
          </div>
          
          <div class="info-row" v-if="exam.description">
            <div class="info-item full-width">
              <span class="label">考试说明：</span>
              <div class="description">{{ exam.description }}</div>
            </div>
          </div>
        </div>
        
        <el-divider></el-divider>
        
        <div class="action-area">
          <el-button 
            type="primary" 
            @click="handleEdit" 
            v-if="exam.status === 0 && hasEditPermission">
            编辑考试
          </el-button>
          <el-button 
            type="danger" 
            @click="handleDelete" 
            v-if="exam.status === 0 && hasEditPermission">
            删除考试
          </el-button>
          <el-button 
            type="success" 
            @click="viewResults" 
            v-if="exam.status === 1 || exam.status === 2">
            查看成绩
          </el-button>
        </div>
        
        <el-divider v-if="showParticipants"></el-divider>
        
        <!-- 参与人员列表 -->
        <div v-if="showParticipants" class="participants-section">
          <h3>参与人员</h3>
          
          <el-table
            :data="participants"
            style="width: 100%"
            border>
            <el-table-column
              prop="studentName"
              label="学生姓名"
              width="150">
            </el-table-column>
            
            <el-table-column
              prop="studentId"
              label="学号"
              width="150">
            </el-table-column>
            
            <el-table-column
              prop="schoolName"
              label="学校"
              width="150">
            </el-table-column>
            
            <el-table-column
              prop="className"
              label="班级"
              width="150">
            </el-table-column>
            
            <el-table-column
              label="参加状态"
              width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.hasSubmitted ? 'success' : 'info'">
                  {{ scope.row.hasSubmitted ? '已参加' : '未参加' }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column
              prop="score"
              label="成绩"
              width="100">
              <template slot-scope="scope">
                {{ scope.row.hasSubmitted ? scope.row.score : '-' }}
              </template>
            </el-table-column>
            
            <el-table-column
              label="提交时间"
              width="180">
              <template slot-scope="scope">
                {{ scope.row.hasSubmitted ? formatDateTime(scope.row.submitTime) : '-' }}
              </template>
            </el-table-column>
            
            <el-table-column
              label="操作"
              width="120">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="viewStudentResult(scope.row)"
                  v-if="scope.row.hasSubmitted">
                  查看答卷
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="participantsQuery.page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="participantsQuery.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="participantsTotal">
            </el-pagination>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getExamDetail, deleteExam } from '@/api/exam';
import { getExamResultList } from '@/api/exam';
import { mapGetters } from 'vuex';

export default {
  name: 'ExamDetail',
  data() {
    return {
      loading: false,
      exam: {
        id: null,
        title: '',
        subjectId: null,
        subjectName: '',
        educationLevel: null,
        educationLevelName: '',
        paperId: null,
        paperTitle: '',
        duration: 0,
        totalScore: 0,
        startTime: '',
        endTime: '',
        schoolId: null,
        schoolName: '',
        status: 0,
        statusName: '',
        description: ''
      },
      showParticipants: false,
      participants: [],
      participantsTotal: 0,
      participantsQuery: {
        page: 1,
        size: 10,
        examId: null
      }
    };
  },
  computed: {
    ...mapGetters([
      'roles'
    ]),
    hasEditPermission() {
      // 只有教师和管理员可以编辑考试
      return this.roles.includes(1) || this.roles.includes(2);
    }
  },
  created() {
    this.getExamDetail();
  },
  methods: {
    // 获取考试详情
    getExamDetail() {
      this.loading = true;
      const examId = this.$route.params.id;
      if (!examId) {
        this.$message.error('考试ID不能为空');
        this.$router.push('/exams');
        return;
      }
      
      this.participantsQuery.examId = examId;
      
      getExamDetail(examId).then(response => {
        this.exam = response.data;
        
        // 如果考试已经开始或结束，显示参与人员
        if (this.exam.status === 1 || this.exam.status === 2) {
          this.showParticipants = true;
          this.getParticipants();
        }
        
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取考试详情失败');
        this.$router.push('/exams');
      });
    },
    // 获取参与人员
    getParticipants() {
      getExamResultList(this.participantsQuery).then(response => {
        this.participants = response.data.records;
        this.participantsTotal = response.data.total;
      }).catch(() => {
        this.$message.error('获取参与人员失败');
      });
    },
    // 编辑考试
    handleEdit() {
      this.$router.push(`/exam/edit/${this.exam.id}`);
    },
    // 删除考试
    handleDelete() {
      this.$confirm('确定要删除该考试吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteExam(this.exam.id).then(() => {
          this.$message.success('删除成功');
          this.$router.push('/exams');
        }).catch(() => {
          this.$message.error('删除失败');
        });
      }).catch(() => {});
    },
    // 查看成绩
    viewResults() {
      this.$router.push('/exams/results');
    },
    // 查看学生答卷
    viewStudentResult(row) {
      this.$router.push(`/exam/result/${row.resultId}`);
    },
    // 每页条数改变时触发
    handleSizeChange(size) {
      this.participantsQuery.size = size;
      this.getParticipants();
    },
    // 当前页改变时触发
    handleCurrentChange(page) {
      this.participantsQuery.page = page;
      this.getParticipants();
    },
    // 返回列表
    goBack() {
      this.$router.push('/exams');
    },
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    // 获取状态标签类型
    getStatusType(status) {
      switch (status) {
        case 0: return 'info';
        case 1: return 'success';
        case 2: return 'warning';
        default: return '';
      }
    }
  }
};
</script>

<style scoped>
.exam-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.exam-title {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.exam-info {
  margin: 20px 0;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-item {
  flex: 1;
  display: flex;
}

.full-width {
  flex-basis: 100%;
}

.label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
  min-width: 80px;
}

.description {
  white-space: pre-line;
  color: #606266;
  line-height: 1.6;
}

.action-area {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.participants-section {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 